/**
 *
 */
package com.suieqian.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.suieqian.config.Env;
import com.suieqian.entity.User;
import com.suieqian.filter.authFile.IgnorePathHelper;
import com.suieqian.service.ISecurityService;
import com.suieqian.util.Message;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 *
 * @Description: 单点登录过滤器
 * @author: tianhua.xie
 * @Date: 2017年5月14日 上午1:57:19
 *
 */
@WebFilter(filterName = "SSOFilter", urlPatterns = "/*")
@Slf4j
public class SSOFilter implements Filter {

    private FilterConfig filterConfig = null;
    @Value("${sso.cookiename}")
    private String cookiename = "First_SSO_PRJ_ID";
    @Value("${sso.SSOServiceURL}")
    private String SSOServiceURL = null;
    @Value("${sso.SSOLoginPage}")
    private String SSOLoginPage = null;

    @Value("${sso.token}")
    private String authToken = null;

    @Autowired
    private ISecurityService securityService;

    @Resource
    private IgnorePathHelper ignorePathHelper;

    /**
     * 初始化
     *
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        if (filterConfig != null) {
            log.info("SSOFilter:Initializing filter");
        }
    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String result = "failed";
        String requestUri = request.getRequestURL().toString();

        String token = request.getHeader("accesstoken");
        if (Objects.nonNull(authToken) && authToken.equals(token)) {
            result = "OK";
            chain.doFilter(req, res);
            return;
        }

        boolean isIgnore = ignorePathHelper.matches(request);
        if (isIgnore
                || requestUri.indexOf(".css") != -1 || requestUri.indexOf(".js") != -1
                || requestUri.indexOf(".jpg") != -1 || requestUri.indexOf(".gif") != -1
                || requestUri.indexOf("/script") != -1 || requestUri.indexOf("/image") != -1
                || requestUri.indexOf(".jpeg") != -1 || requestUri.indexOf(".png") != -1
                || requestUri.indexOf("/common") != -1

                || requestUri.indexOf("/image_inf") != -1 || requestUri.indexOf("/index.jsp") != -1
                || requestUri.indexOf("/assets") != -1 || requestUri.indexOf("/fonts/") != -1
                || requestUri.indexOf("/easyui_1.5/") != -1 || requestUri.indexOf("/layer/") != -1
        ) {
            chain.doFilter(req, res);
        } else {
            Cookie[] diskCookies = request.getCookies();
            if (diskCookies != null) {
                for (int i = 0; i < diskCookies.length; i++) {
                    if (diskCookies[i].getName().equals(this.cookiename)) {
                        token = diskCookies[i].getValue();
                    }
                }
            }
            if (StrUtil.isNotBlank(token)) {
                User user = securityService.checkCookie(token);
                if (null != user) {
                    Env.setUser(user);
                    result = "OK";
                }
            }
//			验证是否登录成功过
            if (result.equals("failed")) {
                response.setContentType("application/json");
                Message message = Message.authError("请先登录");
                JSON json = new JSONObject(message);
                response.getWriter().write(json.toJSONString(0));
                return;
            } else {
                chain.doFilter(req, res);
            }
        }
        Env.remove();
    }

    @Override
    public void destroy() {
    }

    public FilterConfig getFilterConfig() {
        return this.filterConfig;
    }

    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }


    private String SSOService(String cookievalue) throws IOException {
        String authAction = "?action=authcookie&cookiename=";
        HttpClient httpclient = new HttpClient();
        String url = this.SSOServiceURL + authAction + cookievalue;
        GetMethod httpget = new GetMethod(url);
        try {
            // 判断cookie是否正确
            httpclient.executeMethod(httpget);
            String result = httpget.getResponseBodyAsString();
            return result;
        } catch (Exception e) {
            log.info(e.getMessage(), e);
            return "";
        } finally {
            httpget.releaseConnection();
        }
    }

    private void logoutService(String cookievalue) throws IOException {
        String authAction = "?action=logout&cookiename=";
        HttpClient httpclient = new HttpClient();
        GetMethod httpget = new GetMethod(this.SSOServiceURL + authAction + cookievalue);
        try {
            // 注销登录
            httpclient.executeMethod(httpget);
            httpget.getResponseBodyAsString();
        } finally {
            httpget.releaseConnection();
        }
    }

    public void log(String msg) {
        this.filterConfig.getServletContext().log(msg);
    }
}
